import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

import { removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";

// create an axios instance
const service = axios.create({
  baseURL: " http://42.192.15.126:8081/api", // url = base url + request url  
  // baseURL: ' http://192.168.0.125:8000/api', // url = base url + request url
  // baseURL: "http://127.0.0.1:8000/api",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 2000, // request timeout
});
// request interceptor
service.interceptors.request.use(
  (config) => {
    // console.log(config.code);
    NProgress.start(); // 展示进度条  
    config.headers["Authorization"] =
      "Bearer " + window.localStorage.getItem("token");
    return config;
  },
  (error) => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    // return response
    const res = response.data;
    // token过期，重返登录界面
    if (res.code == 401 || res.code == 400) {
      alert("token已经过期,请重新登录");
      store.commit("user/SET_TOKEN", "");
      store.commit("user/SET_ROLES", []);
      localStorage.clear();
      removeToken();
      resetRouter();
      store.dispatch("tagsView/delAllViews", null, { root: true });
      router.push("/login");
    }
    NProgress.done(); // 展示进度条
    return response.data;
    // // if the custom code is not 20000, it is judged as an error.
  },
  (error) => {
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
